package com.tarena.demo.luban.all.main.controller;



import com.tarena.demo.luban.commons.exception.BusinessDemoException;
import com.tarena.demo.luban.commons.restful.JsonResult;
import com.tarena.demo.luban.commons.restful.ResponseCode;
import com.tarena.demo.luban.protocol.order.param.OrderAddParam;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/base/order")
@Api(tags = "订单")
public class OrderController {
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/add")
    @ApiOperation("新增订单的功能")
    public JsonResult addOrder(OrderAddParam orderAddParam){

        ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
        String orderKey = "order:sn:"+orderAddParam.getOrderSn();
        Long increment = opsForValue.increment(orderKey);
        if(increment>1){
            return JsonResult.failed(new BusinessDemoException(ResponseCode.BAD_REQUEST,"重复提交订单"));
        }

        Message<OrderAddParam> message = MessageBuilder.withPayload(orderAddParam).build();

        rocketMQTemplate.asyncSend("order-add-topic", message, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
            }

            @Override
            public void onException(Throwable throwable) {
                // 处理失败信息存储 延迟2秒钟
            }
        });
        return JsonResult.ok("新增订单完成!");
    }

}

